import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/components/Login'
import Home from '@/components/Home'
import Welcome from '@/components/Welcome'
import Users from '@/components/user/Users'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    component: Login,
    name: Login
  },
  {
    path: '/home',
    component: Home,
    name: Home,
    // 进入home  重定向到 welcome
    redirect: '/welcome',
    children: [
      {
        path: '/welcome',
        component: Welcome,
        name: Welcome
      },
      {
        path: '/users',
        component: Users,
        name: Users
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 为路由对象，添加 beforeEach 导航守卫
// to 代表将要访问的路径 from 代表从哪个页面跳转过来
// next函数代表放行 next() 放行 next('/login') 强制跳转
router.beforeEach((to, from, next) => {
// 如果用户访问的登录页，直接放行
  if (to.path === '/login') return next()
  // 从sessionStorage 中获取到 保存的 token 值
  const tokenStr = window.sessionStorage.getItem('token')
  // 没有token，强制跳转到登录页
  if (!tokenStr) return next('/login')
  next()
})

export default router
